import { DatePipe } from '@angular/common';
import { ReportHistoriesComponent } from './../../../@shared/components/report-histories/report-histories.component';
import { Component, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { DataTableComponent, DialogService, TableWidthConfig } from 'ng-devui';
import { SharedMethodService } from 'src/app/@core/services/Sharedmethod/shared-method.service';
import { JobOrderService } from 'src/app/@core/services/jobOrder/job-order.service';

@Component({
  selector: 'app-product-work-report-order',
  templateUrl: './product-work-report-order.component.html',
  styleUrls: ['./product-work-report-order.component.scss']
})
export class ProductWorkReportOrderComponent {
  msgs: Array<Object> = []
  tableData:any[]=[
    {}
  ]
  dataTableOptions={
    columns:[
      {
        field: '工单号',
        header: '工单号',
        fieldType: 'text',
      },

      {
        field: '销售单号',
        header: '销售单号',
        fieldType: 'text',
      },
      {
        field: '销售单号',
        header: '工序序号',
        fieldType: 'text',
      },
      {
        field: '工序编码',
        header: '工序编码',
        fieldType: 'text',
      },
      {
        field: '工序名称',
        header: '工序名称',
        fieldType: 'text',
      },
      {
        field: '产品编码',
        header: '产品编码',
        fieldType: 'text',
      },
      {
        field: '产品名称',
        header: '产品名称',
        fieldType: 'text',
      },
      {
        field: '产品规格',
        header: '产品规格',
        fieldType: 'text',
      },
      {
        field: '操作工',
        header: '操作工',
        fieldType: 'text',
      },
      {
        field: '状态',
        header: '状态',
        fieldType: 'text',
      },
      {
        field: '计划数',
        header: '计划数',
        fieldType: 'text',
      },

      {
        field: '完成进度',
        header: '完成进度',
        fieldType: 'text',
      },
      {
        field: '剩余数',
        header: '剩余数',
        fieldType: 'text',
      },
      {
        field: '计划开工时间',
        header: '计划开工时间',
        fieldType: 'text',
      },
      {
        field: '计划完工时间',
        header: '计划完工时间',
        fieldType: 'text',
      },
      {
        field: '实际开工时间',
        header: '实际开工时间',
        fieldType: 'text',
      },
      {
        field: '实际完工时间',
        header: '实际完工时间',
        fieldType: 'text',
      },
      {
        field: '备注',
        header: '备注',
        fieldType: 'text',
      },
    ]
  }
  tableWidthConfig: TableWidthConfig[] = [
    {
      field:'操作',
      width:'100px'
    },
    {
      field: '工单号',
      width: '140px'
    },
    {
      field: '销售单号',
      width: '180px'
    },
    {
      field: '工序序号',
      width: '80px'
    },

    {
      field: '工序编码',
      width: '150px'
    },
    {
      field: '工序名称',
      width: '100px'
    },
    {
      field: '规格型号',
      width: '100px'
    },
    {
      field: '工序序号',
      width: '100px'
    },
    {
      field: '工序',
      width: '100px'
    },
    {
      field: '操作工',
      width: '100px'
    },
    {
      field: '状态',
      width: '100px'
    },
    {
      field: '计划数',
      width: '100px'
    },
    {
      field: '完成进度',
      width: '150px'
    },
    {
      field: '剩余数',
      width: '100px'
    },
    {
      field: '计划开工时间',
      width: '150px'
    },
    {
      field: '计划完工时间',
      width: '150px'
    },
    {
      field: '实际开工时间',
      width: '150px'
    },
    {
      field: '实际完工时间',
      width: '150px'
    },
  ]
  checkedIds = []
  pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20
  };
  options=[
    '已完工',
    '未完工',
    '未开工',
  ]
  PartNum:string = null;
  PartName:string = null;
  JobOrderNum:string = null;
  JobOrderStatus:string = null;
  ProcessNum:string = null;
  ProcessName:string = null;
  pageSizeOptions = [10, 20, 30, 50, 100];
  productJob=[]
  @ViewChild(DataTableComponent, { static: true }) datatable: DataTableComponent;
  isIconRotated = false;
  constructor(private SharedMethodService:SharedMethodService,private JobOrderService:JobOrderService,private Router:Router,private DialogService:DialogService) { }
  ngOnInit(): void {
    this.PartNum = null;
    this.PartName = null;
    this.JobOrderNum = null;
    this.ProcessNum = null;
    this.ProcessName = null;
    this.JobOrderStatus = '已派工';
    this.JobOrderService.GetJobOrdersProcess2(this.PartNum,this.PartName,this.JobOrderNum,this.JobOrderStatus,this.ProcessNum,this.ProcessName,this.pager.pageIndex,this.pager.pageSize,null,true).subscribe((data:any)=>{
      this.tableData = data.items
      this.pager.total = data.totalCount
    })
  }
  pageIndexChange($event: any) {
   this.search()
  }//切换页码
  pageSizeChange($event: any){
    this.search()
  }//改变每页显示数量
  showToast(type: any,summary:any,content:any) {
    switch (type) {
    default:
      this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  cleared(){
    this.SharedMethodService.cleared(this.checkedIds,this.tableData,this.datatable).subscribe((data:any)=>{
      this.checkedIds=data;
    })
  }
  onRowCheckChange(checked: any, rowIndex: any, nestedIndex: any, rowItem: { $checked: any; $halfChecked: boolean; }){
    this.SharedMethodService.onRowCheckChange(checked, rowIndex, nestedIndex, rowItem,this.datatable)
  }//单选
  getCheckedRows() {
    this.SharedMethodService.getCheckedRows(this.datatable,'warehouseId').subscribe((data:any)=>{
      this.checkedIds=data;
    })

  }//获取选中行
  search2(){
    this.pager.pageIndex = 1
    this.JobOrderService.GetJobOrdersProcess2(this.PartNum,this.PartName,this.JobOrderNum,this.JobOrderStatus,this.ProcessNum,this.ProcessName,this.pager.pageIndex,this.pager.pageSize,null,true).subscribe((data:any)=>{
      this.tableData = data.items
      this.pager.total = data.totalCount
    })
  }
  search(){
    this.JobOrderService.GetJobOrdersProcess2(this.PartNum,this.PartName,this.JobOrderNum,this.JobOrderStatus,this.ProcessNum,this.ProcessName,this.pager.pageIndex,this.pager.pageSize,null,true).subscribe((data:any)=>{
      this.tableData = data.items
      this.pager.total = data.totalCount
    })
  }
  reset(){
    this.PartNum = null;
    this.PartName = null;
    this.JobOrderNum = null;
    this.ProcessNum = null;
    this.ProcessName = null;
    this.JobOrderStatus = '已派工';
    this.JobOrderService.GetJobOrdersProcess2(this.PartNum,this.PartName,this.JobOrderNum,this.JobOrderStatus,this.ProcessNum,this.ProcessName,this.pager.pageIndex,this.pager.pageSize,null,true).subscribe((data:any)=>{
      this.tableData = data.items
      this.pager.total = data.totalCount
    })
  }
  reportHistories(dialogtype?:string){
    const results = this.DialogService.open({
      title: '报工历史',
      width: '1000px',
      data:{
        data:{
          PageNumber: 1,
          PageSize: 20
        },
        title:'报工记录'
      },
      content: ReportHistoriesComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  reportHistory(rowitem:any,dialogtype?:string){
    const results = this.DialogService.open({
      title: '报工历史',
      data:{
        data:{
          JobOrderNum: rowitem.jobOrderNum,
          ProcessNum: rowitem.processNum,
          PageNumber: 1,
          PageSize: 20
        },
        title:'任务报工记录'
      },
      content: ReportHistoriesComponent,
      dialogtype: dialogtype,
      width: '800px',
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  getNames(rowItem: any): string {
    if (rowItem.users) {
      return rowItem.users.map((user: { name: any; }) => user.name).join('，');
    } else {
      return '';
    }
  }
  formatDate(date: Date): string {
    const pipe = new DatePipe('en-US'); // 使用你的语言环境
    return pipe.transform(date, 'yyyy-MM-dd HH:mm:ss');
  }

  // ================= 打印：工时填报（单选） =================
  printSelected(): void {
    if (!this.datatable) {
      this.showToast('warning', '提示', '表格尚未初始化');
      return;
    }
    const rows = this.datatable.getCheckedRows?.() || [];
    if (!rows.length) {
      this.showToast('warning', '提示', '请勾选一条记录后再打印');
      return;
    }
    if (rows.length > 1) {
      this.showToast('warning', '提示', '仅支持选择一条记录进行打印');
      return;
    }
    const row = rows[0];
    const html = this.buildWorkReportPrintHtml(row);
    this.printWithIframe(html);
  }

  private printWithIframe(html: string) {
    const iframe = document.createElement('iframe');
    iframe.style.position = 'fixed';
    iframe.style.right = '0';
    iframe.style.bottom = '0';
    iframe.style.width = '0';
    iframe.style.height = '0';
    iframe.style.border = '0';
    iframe.style.visibility = 'hidden';
    document.body.appendChild(iframe);

    const doc = iframe.contentDocument || (iframe.contentWindow as any)?.document as Document | undefined;
    if (!doc) {
      iframe.parentNode?.removeChild(iframe);
      return;
    }
    doc.open();
    doc.write(html);
    doc.close();

    setTimeout(() => {
      try {
        iframe.contentWindow?.focus();
        iframe.contentWindow?.print();
      } finally {
        setTimeout(() => {
          iframe.parentNode?.removeChild(iframe);
        }, 400);
      }
    }, 200);
  }

  private fmtDateStr(input: any, withTime = false): string {
    if (!input) return '';
    const d = new Date(input);
    if (isNaN(d.getTime())) return String(input);
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const da = String(d.getDate()).padStart(2, '0');
    if (!withTime) return `${y}-${m}-${da}`;
    const hh = String(d.getHours()).padStart(2, '0');
    const mm = String(d.getMinutes()).padStart(2, '0');
    const ss = String(d.getSeconds()).padStart(2, '0');
    return `${y}-${m}-${da} ${hh}:${mm}:${ss}`;
  }

  private to2(n: any): string {
    const x = Number(n);
    if (isNaN(x)) return n == null ? '' : String(n);
    return x.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  }

  private buildWorkReportPrintHtml(row: any): string {
    const now = this.fmtDateStr(new Date(), true);
    const style = `
      <style>
        @page { size: A4; margin: 12mm; }
        * { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', 'PingFang SC', 'Microsoft YaHei', sans-serif; }
        .sheet { width: 210mm; min-height: 297mm; margin: 0 auto; }
        .header { display: grid; grid-template-columns: 1fr auto; align-items: center; }
        .title { font-size: 20px; font-weight: 700; }
        .meta { font-size: 12px; color: #555; }
        table { width: 100%; border-collapse: collapse; margin-top: 8px; }
        th, td { border: 1px solid #333; padding: 6px 8px; font-size: 12px; }
        th { background: #f5f7fa; }
        .grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px 12px; margin-top: 8px; }
        .grid .cell { font-size: 12px; }
        .remark { margin-top: 10px; white-space: pre-wrap; }
        .footer { margin-top: 24px; display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; }
        .footer .cell { font-size: 12px; color: #555; }
      </style>
    `;

    const safe = (v: any) => (v ?? '') as string;
    const userNames = row?.users ? row.users.map((u: any) => u?.name).filter(Boolean).join('、') : '';
    const title = '工单队列';

    const head = `
      <table>
        <colgroup>
          <col style="width: 15%"/><col style="width: 35%"/>
          <col style="width: 15%"/><col style="width: 35%"/>
        </colgroup>
        <tbody>
          <tr><th>工单号</th><td>${safe(row?.jobOrderNum || row?.jobNum || row?.jobOrderNo)}</td><th>销售单号</th><td>${safe(row?.saleOrderNum) || '/'}</td></tr>
          <tr><th>产品编码</th><td>${safe(row?.productNum)}</td><th>产品名称</th><td>${safe(row?.productName)}</td></tr>
          <tr><th>规格型号</th><td>${safe(row?.partType)}</td><th>工序</th><td>${safe(row?.processNum)} ${safe(row?.processName)}</td></tr>
          <tr><th>工序序号</th><td>${safe(row?.processNumber)}</td><th>操作工</th><td>${safe(userNames)}</td></tr>
          <tr><th>计划数量</th><td>${safe(row?.productionQuantity)}</td><th>合格数</th><td>${safe(row?.qualifiedAmount)}</td></tr>
          <tr><th>计划开工</th><td>${safe(this.fmtDateStr(row?.planStartTime, true))}</td><th>计划完工</th><td>${safe(this.fmtDateStr(row?.planFinishTime, true))}</td></tr>
          <tr><th>实际开工</th><td>${safe(this.fmtDateStr(row?.actualStartTime, true))}</td><th>实际完工</th><td>${safe(this.fmtDateStr(row?.actualFinishTime, true))}</td></tr>
        </tbody>
      </table>
    `;

    const html = `
      <!doctype html>
      <html>
        <head>
          <meta charset="utf-8" />
          <title>${title}</title>
          ${style}
        </head>
        <body>
          <div class="sheet">
            <div class="header">
              <div class="title">${title}</div>
              <div class="meta">打印时间：${now}</div>
            </div>
            ${head}
            <div class="footer">
              <div class="cell">制单人：</div>
              <div class="cell">制单时间：</div>
              <div class="cell">审核人：</div>
              <div class="cell">审核时间：</div>
            </div>
          </div>
        </body>
      </html>
    `;
    return html;
  }
}
